package com.zzc.hankz.binding;

import cn.hutool.core.lang.ClassScanner;
import com.zzc.hankz.session.Configuration;
import com.zzc.hankz.session.SqlSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 映射注册机
 *
 * @author：zzc
 * @date: 2022/4/10
 */
public class MapperRegistry {

    private Configuration config;

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

    /**
     * 将已添加的映射器代理加到HashMap中
     */
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type" + type + "is not known to the MapperRegistry");
        }

        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause:" + e, e);
        }

    }

    /**
     * 注册mapper
     *
     * @param type mapper接口
     * @param <T>
     */
    public <T> void addMapper(Class<T> type) {
        /*mapper必须是接口才会注册*/
        if (type.isInterface()) {
            if (hasMapper(type)) {
                //如果重复添加了，报错
                throw new RuntimeException("Type " + type + " is already known to MapperRegistry.");
            }

            // 注册映射器代理工厂
            knownMappers.put(type, new MapperProxyFactory<>(type));
        }
    }

    /**
     * 扫描mapper接口包名 并注册
     *
     * @param packageName 包名
     */
    public void addMappers(String packageName) {
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }

    public  <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }
}
